from exts import db
import apps
from celery import Celery

app = apps.create_app()

from flask_script import Manager, Server
from flask_migrate import Migrate
import datetime


manage = Manager(app)
manage.add_command("runserver", Server(host="0.0.0.0", port=5000, use_debugger=True))
migrate = Migrate(app, db, render_as_batch=True)


def make_celery(app_name):
    CELERY_BROKER_URL = "redis://127.0.0.1:6379/1"
    CELERY_RESULT_BACKEND = "redis://127.0.0.1:6379/2"
    CELERYBEAT_SCHEDULE = {
        'run_build_index': {
            'task': 'apps.basic.views.build_index',
            'schedule': datetime.timedelta(seconds=60)  # 定时任务间隔，这里设置为60秒
        },
    }
    celery_app = Celery(app_name, broker=CELERY_BROKER_URL, backend=CELERY_RESULT_BACKEND,
                        include=["apps.basic.views"]
                        )

    celery_app.conf.beat_schedule = CELERYBEAT_SCHEDULE
    celery_app.conf.update(app.config)
    celery_app.conf.timezone = "UTC"
    return celery_app


my_celery = make_celery(__name__)
app = apps.create_app(celery=my_celery)

# 手动添加 db 相关命令
from flask_script import Command, Option
from flask_migrate import init, migrate, upgrade, downgrade, history, stamp


class DBInit(Command):
    def run(self):
        init()
        print("Migration repository initialized")


class DBMigrate(Command):
    option_list = (
        Option('-m', '--message', dest='message', default=None),
        Option('-a', '--autogenerate', dest='autogenerate', action='store_true', default=False)
    )

    def run(self, message=None, autogenerate=False):
        migrate(message=message)
        if message:
            print(f"Migration script generated with message: {message}")
        else:
            print("Migration script generated")
        if autogenerate:
            print("Autogenerate mode enabled")


class DBUpgrade(Command):
    def run(self):
        upgrade()
        print("Database upgraded")


class DBDowngrade(Command):
    def run(self):
        downgrade()
        print("Database downgraded")


class DBHistory(Command):
    def run(self):
        history()
        print("Migration history displayed")


# 创建 db 命令组
db_manager = Manager(usage="Perform database migrations")
db_manager.add_command("init", DBInit())
db_manager.add_command("migrate", DBMigrate())
db_manager.add_command("upgrade", DBUpgrade())
db_manager.add_command("downgrade", DBDowngrade())
db_manager.add_command("history", DBHistory())

manage.add_command("db", db_manager)

if __name__ == '__main__':
    manage.run()
